import os
import shutil

from fastapi import FastAPI, UploadFile
from fastapi.middleware.cors import CORSMiddleware

from Detector.ComprehensiveFaultDetector import ComprehensiveFaultDetector
from Generator.langchain import ReportGenerator
from model.response import Response

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/generate-report")
async def generate_report(data: dict):
    analyzer = ReportGenerator()
    result = analyzer.analyze_power_lines(data["user_input"])

    return Response.success(result)

@app.post("/upload-files")
async def create_upload_files(files: list[UploadFile]):
    for file in files:
        with open(f"/app/data/{file.filename}", "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
    return Response.success({"filenames": [file.filename for file in files]})

@app.get("/fault-analyze")
async def fault_analyze(file_name: str):
    detector = ComprehensiveFaultDetector(file_name, "/app/data")
    results = detector.run_complete_analysis()

    return Response.success([res for res in results if res.fault_detected])

@app.get("/files-list")
async def files_list():
    return Response.success(sorted([file for file in os.listdir("data")]))


if __name__ == '__main__':
    import uvicorn
    uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True, workers=1)